package extensions.prototipador.sprites;

import java.io.IOException;

import org.xmlpull.v1.XmlSerializer;

import android.graphics.Canvas;
import android.graphics.Paint;

public class Rectangle extends Sprite {
	protected Paint _paint;
	
	public Rectangle()
	{
		this(0,0,0,0,0);
	}
	public Rectangle(int x, int y, int width, int height, int color) {
		super(x, y);
		
		_width = width;
		_height = height;		
		_paint = new Paint();
		_paint.setColor(color);
		_paint.setStyle(Paint.Style.FILL);
		_paint.setAlpha(145);
		//_paint.setStyle(Style.STROKE);
	}
	
	@Override
	public void doDraw(Canvas canvas) {
		canvas.drawRect(_x, _y, _x+_width, _y+_height, _paint);
	}
	
	@Override
	public boolean contains(int x, int y) {

		if (x < Math.min(_x, _x+_width))
			return false;
		
		if (x > Math.max(_x, _x+_width))
			return false;
		
		if (y < Math.min(_y, _y+_height))
			return false;
		
		if (y > Math.max(_y, _y+_height))
			return false;
		
		return true;
	}

	public void setSecondPoint(int x, int y) {
		_width = (int) (x-_x);
		_height = (int) (y-_y);
	}
	
	public void verifyPoints()
	{
		_x = Math.min(_x, _x+_width);
		_y = Math.min(_y, _y+_height);
		
		_width = Math.abs(_width);
		_height = Math.abs(_height);
	}
	
	@Override
	public String toString() {
		return "[x:"+(int)_x+" y:"+(int)_y+" w:"+_width+" h:"+_height+"]";
	}
	
	public void setColor(int color)
	{
		_paint.setColor(color);
	}
	
	public void setSize(int w, int h)
	{
		_width = w;
		_height = h;
	}
	
	@Override
	public void setAttribute(String key, String value) {

		if (key.equalsIgnoreCase("color"))
			_paint.setColor(Integer.parseInt(value));

		else if (key.equalsIgnoreCase("alpha"))
			_paint.setAlpha(Integer.parseInt(value));
		else
			super.setAttribute(key, value);
	}
	
	@Override
	public void saveToFile(XmlSerializer parser) throws IllegalArgumentException, IllegalStateException, IOException {
		parser.startTag(null, "rectangle");
		
		super.saveToFile(parser);
		
		parser.attribute(null, "color", _paint.getColor()+"");
		parser.attribute(null, "alpha", _paint.getAlpha()+"");
		
		parser.endTag(null, "rectangle");
	}
}
